<template>
  <div class="body">
    <p class="title">项目管理</p>
    <!-- 输入框内容 -->
    <div class="search_box">
      <div class="input_box">
        <el-input class="element_input" v-model="searchName" @input="searchData" placeholder="请输入角色名称"></el-input>
        <div>
          <el-badge :value="recycleData.length" :max="100" class="item">
            <el-button type="danger" class="callback" @click="recycle = true">回收站</el-button>
          </el-badge>
          <el-button type="primary" class="new_btn" @click="addPop(formRef)">新增</el-button>
        </div>
      </div>
    </div>
    <el-table :data="pageCount" style="width: 100%; margin-top: 20px; margin-bottom: 20px;"
      :show-overflow-tooltip="true" row-key="id" border stripe="boolean">
      <el-table-column prop="id" label="序号" align="center" width="100" />
      <el-table-column prop="title" label="项目名称" align="center" />
      <el-table-column prop="companyid" label="公司标识" align="center" />
      <el-table-column prop="account" label="公司名称" align="center" />
      <el-table-column prop="address" label="项目地址" align="center" />
      <el-table-column prop="start_time" label="开始时间" align="center" />
      <el-table-column prop="end_time" label="结束时间" align="center" />
      <el-table-column label="操作" align="center" width="250">
        <template #default="scope">
          <div style="display: flex; align-items: center;justify-content: center;">
            <el-button class="btn" type="primary" @click="editData(scope.row)">编辑</el-button>
            <el-button class="btn" @click="undercarriageShow(scope.row.id)" type="danger">下架</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="page_box">
      <el-pagination @size-change="pageNum" @current-change="pageChange" node-key="id" :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100, 200]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.length" />
    </div>
    <div class="bottom_box"></div>

    <el-dialog v-model="dialogVisible" title="添加" width="1000">
      <el-form ref="formRef" :model="employeeForm" :rules="formRules" label-position="right">
        <!-- 单行表单项 -->
        <el-form-item prop="company" label="项目所属公司" class="form-row">
          <el-select v-model="employeeForm.company" clearable placeholder="请选择公司" style="width: 100%">
            <el-option v-for="item in companyData" :key="item.id" :label="item.account" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item prop="title" label="项目名称" class="form-row">
          <el-input v-model="employeeForm.title" placeholder="请输入项目名称" clearable />
        </el-form-item>

        <el-form-item prop="address" label="项目地址" class="form-row">
          <el-input v-model="employeeForm.address" placeholder="请输入项目地址" clearable />
        </el-form-item>

        <el-form-item prop="time" label="项目周期" class="form-row">
          <el-date-picker v-model="employeeForm.time" value-format="YYYY-MM-DD" type="datetimerange" range-separator="-"
            start-placeholder="开始时间" end-placeholder="结束时间" style="width: 100%" />
        </el-form-item>

        <!-- 双列表单项 -->
        <div class="form-row-group">
          <el-form-item prop="operator_account" label="操作员账号" class="form-row">
            <el-input v-model="employeeForm.operator_account" placeholder="操作员账号" clearable />
          </el-form-item>
          <el-form-item prop="operator_pass" label="操作员密码" class="form-row">
            <el-input v-model="employeeForm.operator_pass" placeholder="操作员密码" clearable />
          </el-form-item>
        </div>

        <div class="form-row-group">
          <el-form-item prop="accountant_account" label="项目会计账号" class="form-row">
            <el-input v-model="employeeForm.accountant_account" placeholder="项目会计账号" clearable />
          </el-form-item>
          <el-form-item prop="accountant_pass" label="项目会计密码" class="form-row">
            <el-input v-model="employeeForm.accountant_pass" placeholder="项目会计密码" clearable />
          </el-form-item>
        </div>

        <div class="form-row-group">
          <el-form-item prop="manager_account" label="项目经理账号" class="form-row">
            <el-input v-model="employeeForm.manager_account" placeholder="项目经理账号" clearable />
          </el-form-item>
          <el-form-item prop="manager_pass" label="项目经理密码" class="form-row">
            <el-input v-model="employeeForm.manager_pass" placeholder="项目经理密码" clearable />
          </el-form-item>
        </div>
        <el-form-item label="个人社保基数" class="form-row">
          <el-input v-model="employeeForm.gr_security" placeholder="请输入个人社保基数" clearable />
        </el-form-item>
        <el-form-item label="公司社保基数" class="form-row">
          <el-input v-model="employeeForm.dw_security" placeholder="请输入公司社保基数" clearable />
        </el-form-item>
        <el-form-item label="项目介绍" style="margin-left: 5.5%;">
          <Editor />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false; formRef?.resetFields();">取消</el-button>
          <el-button type="primary" @click="appendData(formRef)">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="recycle" title="项目回收站" width="1100">
      <div class="input_box">
        <el-input class="element_input" v-model="Recycletitle" @input="searchrecycle" placeholder="请输入项目名称"></el-input>
      </div>
      <el-table :data="recyclepageCount" style="width: 100%; margin-top: 20px; margin-bottom: 20px;"
        :show-overflow-tooltip="true" row-key="id" border stripe="boolean">
        <el-table-column prop="id" label="序号" align="center" width="100" />
        <el-table-column prop="title" label="项目名称" align="center" />
        <el-table-column prop="companyid" label="公司标识" align="center" />
        <el-table-column prop="account" label="公司名称" align="center" />
        <el-table-column prop="address" label="项目地址" align="center" />
        <el-table-column prop="start_time" label="开始时间" align="center" />
        <el-table-column prop="end_time" label="结束时间" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <div style="display: flex; align-items: center;justify-content: center;">
              <el-button type="primary" @click="ShelvesShow(scope.row.id)">恢复</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="page_box">
        <el-pagination @size-change="recyclepageNum" @current-change="recyclepageChange" node-key="id"
          :current-page="recycleCurrentPage" :page-sizes="[10, 20, 50, 100, 200]" :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="recyclePage.length" />
      </div>
    </el-dialog>

    <!-- 下架弹窗显示 -->
    <el-dialog v-model="undercarriage" title="下架" width="500">
      <div class="delete_title">
        <img src="/src/assets/warn.png" alt="">
        <span>确定要下架当前项目吗?</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="">取消</el-button>
          <el-button type="primary" @click="takedown">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 上架弹窗显示 -->
    <el-dialog v-model="Shelves" title="恢复" width="500">
      <div class="delete_title">
        <img src="/src/assets/warn.png" alt="">
        <span>确定要恢复当前项目吗?</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="">取消</el-button>
          <el-button type="primary" @click="regain">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, defineAsyncComponent } from 'vue';// 引入ref和computed
import { itemList, companyList, itemAdd, itemEdit, itemshelves, itemRenew } from '/@/api/login/index';//引入当前的接口封装
import type { FormInstance, FormRules, UploadFile, } from 'element-plus';
import { ElMessage } from 'element-plus';
import { log } from 'console';

// 引入组件
const Editor = defineAsyncComponent(() => import('/@/components/editor/index.vue'));
// 全局数据
const data = ref<any[]>([]);
const pageData = ref<any[]>([]);
// 回收站数据
const recycleData = ref<any[]>([]);
const recyclePage = ref<any[]>([]);
// 回收站分页
const recycleCurrentPage = ref(1);
const recyclePageSize = ref(10);
// 声明当前公司数据
const companyData = ref<any[]>([]);
// 声明当前的页码
const currentPage = ref(1);
// 声明当前页面渲染的数据条数
const pageSize = ref(10);
// 编辑添加状态
const editStatus = ref(false);
// 回收站
const recycle = ref(false);

// 下架弹窗状态
const undercarriage = ref(false);
// 上架弹窗状态
const Shelves = ref(false);

// 列表接口请求
itemList({ status: 0 }).then((res) => {
  console.log(res);
  data.value = res.data;
  pageData.value = res.data;
});

itemList({ status: 1 }).then((res) => {
  recycleData.value = res.data;
  recyclePage.value = res.data;
});

// 公司列表接口请求
companyList().then(res => {
  console.log(res.data);
  companyData.value = res.data;
})

// 回收站计算分页数据
const recyclepageCount = computed(() => {
  const start = (recycleCurrentPage.value - 1) * recyclePageSize.value;
  const end = start + recyclePageSize.value;
  return recyclePage.value.slice(start, end);
});

// 页回收站码改变事件
const recyclepageChange = (val: any) => {
  recycleCurrentPage.value = val;
};

// 回收站每页条数改变事件
const recyclepageNum = (val: any) => {
  recyclePageSize.value = val;
  recycleCurrentPage.value = 1; // 重置到第一页
};

// 计算分页数据
const pageCount = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return pageData.value.slice(start, end);
});

// 页码改变事件
const pageChange = (val: any) => {
  currentPage.value = val;
};

// 每页条数改变事件
const pageNum = (val: any) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置到第一页
};

// 添加弹窗的状态
const dialogVisible = ref(false);

// 定义表单数据类型
interface EmployeeForm {
  // 公司
  company: number | null;
  // 项目名称
  title: string;
  // 项目地址
  address: string;
  // 时间
  time: string | any[];
  // 操作员账号密码
  operator_account: string;
  operator_pass: string;
  // 项目会计账号密码
  accountant_account: string;
  accountant_pass: string;
  // 项目经理账号密码
  manager_account: string;
  manager_pass: string;
  // 个人社保基数
  gr_security: string;
  // 公司社保基数
  dw_security: string;
}

// 初始化表单数据
const employeeForm = reactive<EmployeeForm>({
  company: null,
  title: '',
  address: '',
  time: '',
  operator_account: '',
  operator_pass: '',
  accountant_account: '',
  accountant_pass: '',
  manager_account: '',
  manager_pass: '',
  gr_security: '',
  dw_security: '',
})
const formRef = ref<FormInstance>();
// 表单验证规则
const formRules = computed(() => ({
  company: [
    { required: true, message: '请选择公司', trigger: 'blur' },
  ],
  title: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
  ],
  address: [
    { required: true, message: '请输入项目地址', trigger: 'blur' },
  ],
  time: [
    { required: true, message: '请选择时间', trigger: 'blur' },
  ],
  operator_account: [
    { required: true, message: '请输入操作员账号', trigger: 'blur' },
  ],
  operator_pass: [
    { required: editStatus.value, message: '请输入操作员密码', trigger: 'blur' },
  ],
  accountant_account: [
    { required: true, message: '请输入项目会计账号', trigger: 'blur' },
  ],
  accountant_pass: [
    { required: editStatus.value, message: '请输入项目会计密码', trigger: 'blur' },
  ],
  manager_account: [
    { required: true, message: '请输入项目经理账号', trigger: 'blur' },
  ],
  manager_pass: [
    { required: editStatus.value, message: '请输入项目经理密码', trigger: 'blur' },
  ],
}));
// 添加弹窗显示
const addPop = async (formEl: FormInstance | undefined) => {
  dialogVisible.value = true;
  editStatus.value = true;
}

// 添加确认事件
const appendData = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const formData = {
        projectid: editId.value,
        companyid: employeeForm.company,
        title: employeeForm.title,
        address: employeeForm.address,
        end_time: employeeForm.time[1],
        start_time: employeeForm.time[0],
        account: [JSON.parse(employeeForm.operator_account), JSON.parse(employeeForm.accountant_account), JSON.parse(employeeForm.manager_account)],
        password: [employeeForm.operator_pass, employeeForm.accountant_pass, employeeForm.manager_pass],
        project_type: [1, 2, 3],
        id: editAccountId.value,
      }
      itemAdd(formData).then(res => {
        if (res.code == 1) {
          ElMessage.success('操作成功');
          dialogVisible.value = false;
          // 重置表单
          formRef.value?.resetFields();
        } else {
          ElMessage.error('操作失败');
        }
      }).catch(err => {
        ElMessage.error(err);
      })
    }
  })
}

// 编辑回显事件
const editId = ref(null);
// 回显账号名称
const editAccount = ref<any[]>([]);
// 回显账号id
const editAccountId = ref<any[]>([]);
// 编辑回显函数
const editData = (item: any) => {
  editStatus.value = false;
  // 清空之前的数据
  editAccountId.value = [];
  editAccount.value = [];

  itemEdit({ id: item.id }).then(res => {
    if (res.code == 1) {
      res.account.forEach((account: any) => {
        editAccountId.value.push(account.id);  // 正确使用 push
        editAccount.value.push(account.account);
      });
      employeeForm.operator_account = editAccount.value[0] || '';
      employeeForm.accountant_account = editAccount.value[1] || '';
      employeeForm.manager_account = editAccount.value[2] || '';
      dialogVisible.value = true;
      editId.value = item.id;
      employeeForm.company = item.companyid;
      employeeForm.title = item.title;
      employeeForm.address = item.address;
      employeeForm.time = [item.start_time, item.end_time];
    }
  }).catch(err => {
    ElMessage.error(err.message || '获取账号信息失败');
  });
};
// 上下架id
const ShelvesId = ref(null);
// 下架弹窗显示
const undercarriageShow = (item: any) => {
  console.log(item);
  undercarriage.value = true;
  ShelvesId.value = item;
}
// 恢复弹窗显示
const ShelvesShow = (item: any) => {
  console.log(item);
  Shelves.value = true;
  ShelvesId.value = item;
}
// 下架接口
const takedown = () => {
  itemshelves({ id: ShelvesId.value }).then(res => {
    if (res.code == 1) {
      ElMessage.success('下架成功');
      undercarriage.value = false;
    } else {
      ElMessage.error('操作失败');
    }
  }).catch(err => {
    ElMessage.error(err);
  })
}

// 回复接口
const regain = () => {
  itemRenew({ id: ShelvesId.value }).then(res => {
    if (res.code == 1) {
      ElMessage.success('恢复成功');
      Shelves.value = false;
    } else {
      ElMessage.error('操作失败');
    }
  }).catch(err => {
    ElMessage.error(err);
  })
}
const searchName = ref('');
// 搜索函数
const searchData = () => {
  const filteredData = computed(() => {
    // 无搜索词时返回全部数据
    if (!searchName.value) {
      return pageData.value = data.value;
    }

    return data.value.filter(item => {
      // 检查每个字段是否满足相应条件（如果该搜索条件存在）
      const nameMatch = !searchName.value ||
        (item.title && item.title.toString().toLowerCase().includes(searchName.value.toLowerCase()));
      return nameMatch;
    });
  });
  pageData.value = filteredData.value;
};
const Recycletitle = ref('');

const searchrecycle = () => {
  const filteredData = computed(() => {
    // 无搜索词时返回全部数据
    if (!Recycletitle.value) {
      return recyclePage.value = recycleData.value;
    }

    return recycleData.value.filter(item => {
      // 检查每个字段是否满足相应条件（如果该搜索条件存在）
      const nameMatch = !Recycletitle.value ||
        (item.title && item.title.toString().toLowerCase().includes(Recycletitle.value.toLowerCase()));
      return nameMatch;
    });
  });
  recyclePage.value = filteredData.value;
}

</script>

<style scoped>
.body {
  padding: 20px;
}

.item {
  margin-top: 10px;
  margin-right: 40px;
}

.title {
  font-weight: 400;
  font-size: 25px;
}

.input_box {
  width: 100%;
  display: flex;
  margin-top: 15px;
  align-items: center;
  justify-content: space-between;
}


.element_input {
  width: 15%;
}

.callback {
  height: 35px;
}

.new_btn {
  height: 35px;
  background-color: #0052CC;
  border: 1px solid #0052CC;
}

.new_btn:hover {
  background-color: #4d82d1;
  border: 1px solid #4d82d1;
}

.new_btn:active {
  background-color: #00388b;
  border: 1px solid #00388b;
}

.page_box {
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.type_text {
  padding: 5px 10px;
  background-color: #ECF5FF;
  border: 1px solid #469dff;
  color: #469dff;
  border-radius: 5px;
}

/* 单行表单项样式 */
.form-row {
  display: flex;
  margin-bottom: 20px;
}

/* 标签右对齐 */
.form-row ::v-deep .el-form-item__label {
  text-align: right;
  padding-right: 12px;
  width: 120px;
  /* 固定标签宽度 */
  flex: 0 0 auto;
}

/* 输入框区域 */
.form-row ::v-deep .el-form-item__content {
  flex: 1;
  min-width: 0;
}

/* 双列表单项容器 */
.form-row-group {
  display: flex;
  gap: 20px;
  /* 两列间距 */
  margin-bottom: 20px;
}

/* 双列表单项 */
.form-row-group .form-row {
  flex: 1;
  margin-bottom: 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .form-row-group {
    flex-direction: column;
    gap: 20px;
  }
}

.editor-container {
  padding: 0% !important;
  width: 100%;
  /* 继承表单宽度 */
  border-radius: 4px;
  /* 相同圆角 */
  transition: border-color 0.2s;
  /* 相同过渡效果 */
}

.row_input_box {
  width: 80%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;
}

.bottom_box {
  width: 100%;
  height: 30px;
}

.delete_title {
  display: flex;
}

.delete_title img {
  width: 20px;
  margin-right: 10px;
}

.checkBtn {
  position: absolute;
  top: 0;
  height: 25px;
  line-height: 25px;
  padding: 0px 10px;
  left: 200px;
}

.foldBtn {
  position: absolute;
  top: 0;
  height: 25px;
  line-height: 25px;
  padding: 0px 10px;
  left: 110px;
}

.btn{
  height: 30px;
  padding: 0px 15px;
}
</style>